package com.um.jdy.app.baofu.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.um.jdy.baofu.api.BaoFuAccountService;
import com.um.jdy.baofu.entity.account.ContentBodyEntity;
import com.um.jdy.baofu.entity.account.RsultBodyEntity;
import com.um.jdy.baofu.entity.account.ValuesAcctInfoEntity;
import com.um.jdy.baofu.entity.account.ValuesActionEntity;
import com.um.jdy.baofu.utils.FormatUtil;
import com.um.jdy.common.baofu.entity.po.BaofuAccountDetails;
import com.um.jdy.common.baofu.entity.po.BaofuRefund;
import com.um.jdy.common.baofu.enums.BaofuEnum;
import com.um.jdy.common.baofu.service.BaofuAccountDetailsService;
import com.um.jdy.common.baofu.service.BaofuRefundService;
import com.um.jdy.common.baofu.service.BaofuService;
import com.um.jdy.common.base.enums.YesOrNo;
import com.um.jdy.common.charge.code.OrderCode;
import com.um.jdy.common.charge.entity.po.DataLog;
import com.um.jdy.common.charge.entity.po.DepositOrder;
import com.um.jdy.common.charge.entity.po.EbOrder;
import com.um.jdy.common.charge.entity.po.Order;
import com.um.jdy.common.charge.enums.OrderAction;
import com.um.jdy.common.charge.enums.OrderEnum;
import com.um.jdy.common.charge.enums.OrderException;
import com.um.jdy.common.charge.service.DataLogService;
import com.um.jdy.common.charge.service.DepositOrderService;
import com.um.jdy.common.charge.service.EbOrderService;
import com.um.jdy.common.charge.service.OrderService;
import com.um.jdy.common.commons.service.CommissionService;
import com.um.jdy.common.finance.entity.po.PlatformBill;
import com.um.jdy.common.finance.entity.po.PlatformProfitBill;
import com.um.jdy.common.finance.entity.po.UserBill;
import com.um.jdy.common.finance.enums.FinancialEnum;
import com.um.jdy.common.finance.service.PlatformBillService;
import com.um.jdy.common.finance.service.PlatformProfitBillService;
import com.um.jdy.common.finance.service.UserBillService;
import com.um.jdy.common.member.entity.po.RechargeOrder;
import com.um.jdy.common.member.entity.po.Wallet;
import com.um.jdy.common.member.enums.PayEnum;
import com.um.jdy.common.member.service.RechargeOrderService;
import com.um.jdy.common.member.service.WalletService;
import com.um.jdy.common.month.entity.po.CardOrder;
import com.um.jdy.common.month.entity.po.CardUser;
import com.um.jdy.common.month.service.CardOrderService;
import com.um.jdy.common.month.service.CardUserService;
import com.um.springboot.starter.exception.ServiceException;
import com.um.springboot.starter.orm.manager.BaseManager;
import com.um.springboot.starter.utils.OrderUtil;
import com.um.springboot.starter.utils.PayUtil;
import com.um.springboot.starter.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;

@Component
@Slf4j
public class BaofuRefundManager extends BaseManager<BaofuRefundService> {
    @Autowired
    UserBillService userBillService;

    @Autowired
    PlatformBillService platformBillService;

    @Autowired
    OrderService orderService;

    @Autowired
    EbOrderService ebOrderService;


    @Autowired
    DepositOrderService depositOrderService;

    @Autowired
    DataLogService dataLogService;

    @Autowired
    RechargeOrderService rechargeOrderService;

    @Autowired
    WalletService walletService;

    @Autowired
    PlatformProfitBillService platformProfitBillService;

    @Autowired
    CardOrderService cardOrderService;

    @Autowired
    CardUserService cardUserService;

    @Autowired
    CommissionService commissionService;

    @Autowired
    CommissionService calcCommission;
    @Autowired
    BaofuAccountDetailsService accountDetailsService;
    @Autowired
    private BaofuAccountDetailsService baofuAccountDetailsService;

    @Autowired
    BaoFuAccountService baoFuAccountService;


    //订单结算执行退款
    public void chargeEbRefunZd(String outRefundNo,String refundState,String msg){
        // BaofuRefund baofuRefund = service.getRow("out_refund_no", outRefundNo);
        BaofuRefund baofuRefund = service.getRow(new String[]{"out_refund_no","refund_state"}, new Object[]{outRefundNo,"REFUND"});
        //更新订单状态
        if(baofuRefund != null){
            Order order = orderService.getRow("out_trade_no", baofuRefund.getOutTradeNo());
            if(refundState.equals("SUCCESS")){
                String outTradeNo = order.getOutTradeNo();

                //退款成功逻辑
                //订单实际金额
//                int orderAmount = StringUtil.toInt(order.getPayAmount()) - (StringUtil.toInt(order.getReturnAmount()) + baofuRefund.getRefundAmount());
//                int returnAmount = baofuRefund.getRefundAmount();//本次退回金额
//                order.setReturnAmount(StringUtil.toInt(order.getReturnAmount()) + returnAmount);//已退金额+本次退款金额
//                order.setOrderAmount(orderAmount);
                order.setReturnStatus(OrderEnum.ReturnStatus.Success.name());
                orderService.saveRow(order);
                //插入用户账单流水：退回余额
                UserBill userBill = new UserBill();
                userBill.setComId(order.getComId());
                userBill.setMemberUserId(order.getMemberUserId());
                userBill.setNo(OrderUtil.getOrderNo());
                userBill.setOutTradeNo(order.getOutTradeNo());
                userBill.setOrderNo(order.getOrderNo());
                userBill.setAmount(baofuRefund.getRefundAmount());
                userBill.setType(FinancialEnum.IncomeOrExpend.Income.name());//收入支出类型：0-收入，1-支出
                userBill.setEvent(FinancialEnum.UserBillEvent.Refund.name());
                userBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
                userBill.setCreateTime(DateUtil.date());
                userBillService.saveRow(userBill);

                //插入平台账单流水：充电退回
                PlatformBill platformBill = new PlatformBill();
                platformBill.setComId(order.getComId());
                platformBill.setNo(OrderUtil.getOrderNo());
                platformBill.setOutTradeNo(order.getOutTradeNo());
                platformBill.setOrderNo(order.getOrderNo());
                platformBill.setAmount(baofuRefund.getRefundAmount());
                platformBill.setType(FinancialEnum.IncomeOrExpend.Expend.name());//收入支出类型：0-收入，1-支出
                platformBill.setEvent(FinancialEnum.PlatformBillEvent.OrderRefund.name());
                platformBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
                platformBill.setCreateTime(DateUtil.date());
                platformBillService.saveRow(platformBill);


            }else {
                order.setReturnStatus(OrderEnum.ReturnStatus.Failure.name());//退款失败
                log.error(StrUtil.format("订单{}宝付微信退款异常", baofuRefund.getOutTradeNo()));

                order.setExceptionType(OrderException.EB.RefundFailed.name());
                order.setIsException(YesOrNo.Yes.name());
                order.setExceptionStatus(YesOrNo.No.name());
                orderService.saveRow(order);
                baofuRefund.setErrMsg(msg);
            }
            baofuRefund.setRefundState(refundState);
            service.saveRow(baofuRefund);
        }
    }

    public void chargeEbRefun(String outRefundNo,String refundState,String msg){
       // BaofuRefund baofuRefund = service.getRow("out_refund_no", outRefundNo);
        BaofuRefund baofuRefund = service.getRow(new String[]{"out_refund_no","refund_state"}, new Object[]{outRefundNo,"REFUND"});
        //更新订单状态
        if(baofuRefund != null){
            Order order = orderService.getRow("out_trade_no", baofuRefund.getOutTradeNo());
            if(refundState.equals("SUCCESS")){
                String payPay = StringUtil.getTrim(order.getPayWay());
                String outTradeNo = order.getOutTradeNo();
                if(payPay.equals(PayEnum.PayWay.Deposit.name()) && PayUtil.isProd()){
                    DepositOrder deposit = depositOrderService.getRow("charge_order_id",order.getChargeOrderId());
                    if(null != deposit){
                        deposit.setReturnStatus(OrderEnum.DepositReturnStatus.Yes.name());
                        deposit.setReturnTime(new Date());
                        outTradeNo =deposit.getOutTradeNo();
                        depositOrderService.saveRow(deposit);
                    }
                }
                //退款成功逻辑
                //订单实际金额
//                int orderAmount = StringUtil.toInt(order.getPayAmount()) - (StringUtil.toInt(order.getReturnAmount()) + baofuRefund.getRefundAmount());
//                int returnAmount = baofuRefund.getRefundAmount();//本次退回金额
//                order.setReturnAmount(StringUtil.toInt(order.getReturnAmount()) + returnAmount);//已退金额+本次退款金额
//                order.setOrderAmount(orderAmount);
                order.setReturnStatus(OrderEnum.ReturnStatus.Success.name());
                orderService.saveRow(order);
                //插入用户账单流水：退回余额
                UserBill userBill = new UserBill();
                userBill.setComId(order.getComId());
                userBill.setMemberUserId(order.getMemberUserId());
                userBill.setNo(OrderUtil.getOrderNo());
                userBill.setOutTradeNo(order.getOutTradeNo());
                userBill.setOrderNo(order.getOrderNo());
                userBill.setAmount(baofuRefund.getRefundAmount());
                userBill.setType(FinancialEnum.IncomeOrExpend.Income.name());//收入支出类型：0-收入，1-支出
                userBill.setEvent(FinancialEnum.UserBillEvent.Refund.name());
                userBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
                userBill.setCreateTime(DateUtil.date());
                userBillService.saveRow(userBill);

                //插入平台账单流水：充电退回
                PlatformBill platformBill = new PlatformBill();
                platformBill.setComId(order.getComId());
                platformBill.setNo(OrderUtil.getOrderNo());
                platformBill.setOutTradeNo(order.getOutTradeNo());
                platformBill.setOrderNo(order.getOrderNo());
                platformBill.setAmount(baofuRefund.getRefundAmount());
                platformBill.setType(FinancialEnum.IncomeOrExpend.Expend.name());//收入支出类型：0-收入，1-支出
                platformBill.setEvent(FinancialEnum.PlatformBillEvent.OrderRefund.name());
                platformBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
                platformBill.setCreateTime(DateUtil.date());
                platformBillService.saveRow(platformBill);

                // 校验是否进行分佣
                if (this.checkCommission(order)) {
                    int profit = calcCommission.refundCommission(order.getChargeOrderId(),new Date(), order.getOrderNo(), outTradeNo, baofuRefund.getRefundAmount(),order.getPayAmount());
                    order.setProfit(order.getProfit() - profit);
                }

                //宝付账户减值todo 只支持全部退款
                if(order.getIsBaofuSplit()==1 || order.getIsBaofuFireSplit() ==1){
                    baofuRefund(baofuRefund);
                }

            }else {
                order.setReturnStatus(OrderEnum.ReturnStatus.Failure.name());//退款失败
                log.error(StrUtil.format("订单{}宝付微信退款异常", baofuRefund.getOutTradeNo()));

                order.setExceptionType(OrderException.EB.RefundFailed.name());
                order.setIsException(YesOrNo.Yes.name());
                order.setExceptionStatus(YesOrNo.No.name());
                orderService.saveRow(order);
                baofuRefund.setErrMsg(msg);
            }
            baofuRefund.setRefundState(refundState);
            service.saveRow(baofuRefund);
        }
    }
    public void chargePbRefund(String outRefundNo,String refundState,String msg){
        BaofuRefund baofuRefund = service.getRow("out_refund_no", outRefundNo);
        if(baofuRefund != null){
            DepositOrder depositOrder = depositOrderService.getRow("out_trade_no", baofuRefund.getOutTradeNo());
            if(refundState.equals("SUCCESS")){

                //退款成功逻辑
                    saveChargeData(depositOrder.getComId(), depositOrder.getChargeOrderId(), OrderAction.PB.ReturnDepositOrderSuccess,
                            new HashMap(), "无");
                    //插入用户账单流水：押金提现
                    userBillService.addBill(depositOrder.getComId(), depositOrder.getMemberUserId(), depositOrder.getOutTradeNo(),
                            depositOrder.getOrderNo(), depositOrder.getReturnAmount(), FinancialEnum.IncomeOrExpend.Income,
                            FinancialEnum.UserBillEvent.DepositCashout, FinancialEnum.BillStatus.Effective);

                    //插入平台账单流水：押金提现
                    platformBillService.addBill(depositOrder.getComId(), depositOrder.getOutTradeNo(), depositOrder.getOrderNo(),
                            depositOrder.getReturnAmount(), FinancialEnum.IncomeOrExpend.Expend,
                            FinancialEnum.PlatformBillEvent.DepositCashout, FinancialEnum.BillStatus.Effective);


            }else {
                log.error(StrUtil.format("押金订单[{}]支付宝提现异常", depositOrder.getOrderNo()));
                saveChargeData(depositOrder.getComId(), depositOrder.getChargeOrderId(), OrderAction.PB.RetuenDePositOrderFail,
                        new HashMap(), String.format("开始退回/提现押金失败：%s"));
                baofuRefund.setErrMsg(msg);
            }
            baofuRefund.setRefundState(refundState);
            service.saveRow(baofuRefund);
        }

    }
    /**
     * 保存记录订单操作日志
     * @param orderId 订单ID
     * @param action 操作类型
     * @param data 其他数据
     * @param remark 描述
     */
    public void saveChargeData(String comId, String orderId, OrderAction.PB action, Object data, String remark){
        DataLog dataLog = new DataLog();
        dataLog.setComId(comId);
        dataLog.setChargeOrderId(orderId);
        dataLog.setAction(action.name());
        dataLog.setActionZh(action.getValue());
        dataLog.setCreateTime(DateUtil.date());
        dataLog.setJsonData(cn.hutool.json.JSONUtil.toJsonStr(data));
        dataLog.setRemark(remark);
        dataLogService.saveRow(dataLog);
    }

    public void walletRefund(String outRefundNo,String refundState,String msg){
        //BaofuRefund baofuRefund = service.getRow("out_refund_no", outRefundNo);
        BaofuRefund baofuRefund = service.getRow(new String[]{"out_refund_no","refund_state"}, new Object[]{outRefundNo,"REFUND"});
        if(baofuRefund != null){
            if(refundState.equals("SUCCESS")){
                RechargeOrder order = rechargeOrderService.getRow("out_trade_no", baofuRefund.getOutTradeNo());
                //退款成功逻辑
                    Integer returnAmount = baofuRefund.getRefundAmount();
                    //记录钱包流水：余额提现
                    Wallet memberWallet = new Wallet();
                    memberWallet.setComId(order.getComId());
                    memberWallet.setMemberUserId(order.getMemberUserId());
                    memberWallet.setOrderNo(order.getOrderNo());
                    memberWallet.setNo(OrderUtil.getOrderNo());
                    memberWallet.setAmount(returnAmount);
                    memberWallet.setType(FinancialEnum.IncomeOrExpend.Expend.name());
                    memberWallet.setEvent(FinancialEnum.WalletBillEvent.RechargeRedund.name());
                    memberWallet.setStatus(FinancialEnum.BillStatus.Effective.name());
                    memberWallet.setCreateTime(DateUtil.date());
                    walletService.saveRow(memberWallet);

                    //插入用户账单流水：余额提现
                    UserBill userBill = new UserBill();
                    userBill.setComId(order.getComId());
                    userBill.setMemberUserId(order.getMemberUserId());
                    userBill.setNo(OrderUtil.getOrderNo());
                    userBill.setOutTradeNo(order.getOutTradeNo());
                    userBill.setOrderNo(order.getOrderNo());
                    userBill.setAmount(returnAmount);
                    userBill.setType(FinancialEnum.IncomeOrExpend.Income.name());//收入支出类型：0-收入，1-支出
                    userBill.setEvent(FinancialEnum.UserBillEvent.RechargeRedund.name());
                    userBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
                    userBill.setCreateTime(DateUtil.date());
                    userBillService.saveRow(userBill);

                    //插入平台账单流水：余额提现
                    PlatformBill platformBill = new PlatformBill();
                    platformBill.setComId(order.getComId());
                    platformBill.setNo(OrderUtil.getOrderNo());
                    platformBill.setOutTradeNo(order.getOutTradeNo());
                    platformBill.setOrderNo(order.getOrderNo());
                    platformBill.setAmount(returnAmount);
                    platformBill.setType(FinancialEnum.IncomeOrExpend.Expend.name());//收入支出类型：0-收入，1-支出
                    platformBill.setEvent(FinancialEnum.PlatformBillEvent.PackageRefund.name());
                    platformBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
                    platformBill.setCreateTime(DateUtil.date());
                    platformBillService.saveRow(platformBill);

                    int giftAmount = (int)(order.getGiftAmount() * (returnAmount * 1.0 / order.getPayAmount()));
                    //订单存在赠送金额，则需要按比例退掉赠送金额
                    if(giftAmount > 0){

                        Wallet giftWallet = new Wallet();
                        giftWallet.setComId(order.getComId());
                        giftWallet.setMemberUserId(order.getMemberUserId());
                        giftWallet.setOrderNo(order.getOrderNo());
                        giftWallet.setNo(OrderUtil.getOrderNo());
                        giftWallet.setAmount(giftAmount);
                        giftWallet.setType(FinancialEnum.IncomeOrExpend.Expend.name());
                        giftWallet.setEvent(FinancialEnum.WalletBillEvent.GiftRefund.name());
                        giftWallet.setStatus(FinancialEnum.BillStatus.Effective.name());
                        giftWallet.setCreateTime(DateUtil.date());
                        walletService.saveRow(giftWallet);

                        PlatformProfitBill profitBill = new PlatformProfitBill();
                        profitBill.setComId(order.getComId());
                        profitBill.setNo(OrderUtil.getOrderNo());
                        profitBill.setOutTradeNo(order.getOutTradeNo());
                        profitBill.setOrderNo(order.getOrderNo());
                        profitBill.setAmount(giftAmount);
                        profitBill.setType(FinancialEnum.IncomeOrExpend.Income.name());//收入支出类型：0-收入，1-支出
                        profitBill.setEvent(FinancialEnum.PlatformProfitBillEvent.GiftRefund.name());
                        profitBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
                        profitBill.setCreateTime(DateUtil.date());
                        platformProfitBillService.saveRow(profitBill);
                    }


            }else {
                baofuRefund.setErrMsg(msg);
            }
            baofuRefund.setRefundState(refundState);
            service.saveRow(baofuRefund);
        }

    }

    public void cardRefund(String outRefundNo,String refundState,String msg){
        //cardUserService.getRow(new String[]{"com_id","member_user_id","device_station_id"},new Object[]{comId,userId,stationId});
//        BaofuRefund baofuRefund = service.getRow("out_refund_no", outRefundNo);
        BaofuRefund baofuRefund = service.getRow(new String[]{"out_refund_no","refund_state"}, new Object[]{outRefundNo,"REFUND"});
        if(baofuRefund != null){
            if(refundState.equals("SUCCESS")){
                CardOrder order = cardOrderService.getRow("out_trade_no", baofuRefund.getOutTradeNo());
                //退款成功逻辑
                    //套餐降级
                    CardOrder nextOrder = cardOrderService.getEntity(order.getLastOrderId());
                    if (nextOrder != null) {
                        CardUser cardUser = cardUserService.getEntity(new String[]{"member_user_id","month_card_package_id"},new Object[]{order.getMemberUserId(),order.getMonthCardPackageId()});
                        if(cardUser != null){
                            cardUser.setMonthCardPackageId(nextOrder.getMonthCardPackageId());
                            cardUser.setMaxPower(nextOrder.getMaxPower());
                            cardUserService.saveRow(cardUser);
                        }
                    }else{//已经是最开始订单，则删除用户月卡
                        CardUser cardUser = cardUserService.getEntity(new String[]{"member_user_id","month_card_package_id"},new Object[]{order.getMemberUserId(),order.getMonthCardPackageId()});
                        if(cardUser != null)
                            cardUserService.delete(cardUser.getMonthCardUserId());
                    }

                    //退款金额
                    int returnAmount = baofuRefund.getRefundAmount();

                    //月卡退回
                    UserBill userBill = new UserBill();
                    userBill.setMemberUserId(order.getMemberUserId());
                    userBill.setNo(OrderUtil.getOrderNo());
                    userBill.setOutTradeNo(order.getOutTradeNo());
                    userBill.setOrderNo(order.getOrderNo());
                    userBill.setAmount(returnAmount);
                    userBill.setType(FinancialEnum.IncomeOrExpend.Income.name());//收入支出类型：0-收入，1-支出
                    userBill.setEvent(FinancialEnum.UserBillEvent.MonthCardRefund.name());
                    userBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
                    userBill.setCreateTime(DateUtil.date());
                    userBill.setRemark("后台管理员操作月卡退款");
                    userBill.setComId(order.getComId());
                    userBillService.saveRow(userBill);

                    //插入平台账单流水：充电退回
                    PlatformBill platformBill = new PlatformBill();
                    platformBill.setNo(OrderUtil.getOrderNo());
                    platformBill.setOutTradeNo(order.getOutTradeNo());
                    platformBill.setOrderNo(order.getOrderNo());
                    platformBill.setAmount(returnAmount);
                    platformBill.setType(FinancialEnum.IncomeOrExpend.Expend.name());//收入支出类型：0-收入，1-支出
                    platformBill.setEvent(FinancialEnum.PlatformBillEvent.MonthCardRefund.name());
                    platformBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
                    platformBill.setCreateTime(DateUtil.date());
                    platformBill.setRemark("后台管理员操作月卡退款");
                    platformBill.setComId(order.getComId());
                    platformBillService.saveRow(platformBill);

                    int profit = commissionService.refundMonthCardCommission(order.getMonthCardOrderId(),order.getDeviceStationId(),new Date(),
                            order.getOrderNo(),order.getOutTradeNo(),returnAmount,order.getPayAmount());

                    order.setReturnTime(new Date());
                    order.setReturnStatus(OrderEnum.ReturnStatus.Success.name());
                    order.setReturnAmount(order.getReturnAmount() + returnAmount);
                    order.setProfit(profit);
                    cardOrderService.saveRow(order);

                    //宝付账户减值todo 只支持全部退款
                    if(order.getIsBaofuSplit()==1){
                        baofuRefund(baofuRefund);
                    }
            }else {
                baofuRefund.setErrMsg(msg);
            }
            baofuRefund.setRefundState(refundState);
            service.saveRow(baofuRefund);
        }

    }

    public void depositRefund(String outRefundNo,String refundState,String msg){
        BaofuRefund baofuRefund = service.getRow(new String[]{"out_refund_no","refund_state"}, new Object[]{outRefundNo,"REFUND"});
        if(baofuRefund != null){
            if(refundState.equals("SUCCESS")){
                DepositOrder depositOrder = depositOrderService.getRow("out_trade_no", baofuRefund.getOutTradeNo());
                if(depositOrder != null){
                    depositOrder.setReturnStatus(OrderEnum.DepositReturnStatus.Yes.name());//退款成功
                    depositOrder.setReturnTime(new Date());
                    depositOrderService.saveRow(depositOrder);
                    //插入用户账单流水：押金提现
                    UserBill userBill = new UserBill();
                    userBill.setMemberUserId(depositOrder.getMemberUserId());
                    userBill.setNo(OrderUtil.getOrderNo());
                    userBill.setOutTradeNo(depositOrder.getOutTradeNo());
                    userBill.setOrderNo(depositOrder.getOrderNo());
                    userBill.setAmount(baofuRefund.getRefundAmount());
                    userBill.setType(FinancialEnum.IncomeOrExpend.Income.name());//收入支出类型：0-收入，1-支出
                    userBill.setEvent(FinancialEnum.UserBillEvent.DepositCashout.name());
                    userBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
                    userBill.setCreateTime(DateUtil.date());
                    userBill.setComId(depositOrder.getComId());
                    userBillService.saveRow(userBill);

                    //插入平台账单流水：押金提现
                    PlatformBill platformBill = new PlatformBill();
                    platformBill.setNo(OrderUtil.getOrderNo());
                    platformBill.setOutTradeNo(depositOrder.getOutTradeNo());
                    platformBill.setOrderNo(depositOrder.getOrderNo());
                    platformBill.setAmount(baofuRefund.getRefundAmount());
                    platformBill.setType(FinancialEnum.IncomeOrExpend.Expend.name());//收入支出类型：0-收入，1-支出
                    platformBill.setEvent(FinancialEnum.PlatformBillEvent.DepositCashout.name());
                    platformBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
                    platformBill.setCreateTime(DateUtil.date());
                    platformBill.setComId(depositOrder.getComId());
                    platformBillService.saveRow(platformBill);
                }
                //退款成功逻辑

            }else {
                baofuRefund.setErrMsg(msg);
                log.error(StrUtil.format("押金订单{}微信提现异常", baofuRefund.getOutTradeNo()));
            }
            baofuRefund.setRefundState(refundState);
            service.saveRow(baofuRefund);
        }

    }

    public void rechargeRefund(String outRefundNo,String refundState,String msg){
        BaofuRefund baofuRefund = service.getRow(new String[]{"out_refund_no","refund_state"}, new Object[]{outRefundNo,"REFUND"});
        if(baofuRefund != null){
            if(refundState.equals("SUCCESS")){
                RechargeOrder rechargeOrder = rechargeOrderService.getRow("out_trade_no", baofuRefund.getOutTradeNo());
                //退款成功逻辑
                if(rechargeOrder != null){
                    rechargeOrder.setReturnAmount(rechargeOrder.getReturnAmount() + baofuRefund.getRefundAmount());
                    rechargeOrder.setReturnTime(new Date());
                    rechargeOrderService.saveRow(rechargeOrder);
                    String orderNo = rechargeOrder.getOrderNo();
                    Integer amount = baofuRefund.getRefundAmount();
                    String outTradeNo = rechargeOrder.getOutTradeNo();
                    //记录钱包流水，金额为充值到账金额
                    Wallet wallet = new Wallet();
                    wallet.setMemberUserId(rechargeOrder.getMemberUserId());
                    wallet.setNo(OrderUtil.getOrderNo());
                    wallet.setOrderNo(orderNo);
                    wallet.setAmount(amount);
                    wallet.setType(FinancialEnum.IncomeOrExpend.Expend.name());//收入支出类型：0-收入，1-支出
                    wallet.setEvent(FinancialEnum.UserBillEvent.RechargeRedund.name());
                    wallet.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
                    wallet.setCreateTime(DateUtil.date());
                    wallet.setComId(rechargeOrder.getComId());
                    walletService.saveRow(wallet);

                    //记录账户流水，金额为支付金额
                    UserBill userBill = new UserBill();
                    userBill.setMemberUserId(rechargeOrder.getMemberUserId());
                    userBill.setNo(OrderUtil.getOrderNo());
                    userBill.setOutTradeNo(outTradeNo);
                    userBill.setOrderNo(orderNo);
                    userBill.setAmount(amount);
                    userBill.setType(FinancialEnum.IncomeOrExpend.Income.name());//收入支出类型：0-收入，1-支出
                    userBill.setEvent(FinancialEnum.UserBillEvent.RechargeRedund.name());
                    userBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
                    userBill.setCreateTime(DateUtil.date());
                    userBill.setComId(rechargeOrder.getComId());
                    userBillService.saveRow(userBill);

                    //插入平台账单流水：充值退回
                    PlatformBill platformBill = new PlatformBill();
                    platformBill.setNo(OrderUtil.getOrderNo());
                    platformBill.setOutTradeNo(outTradeNo);
                    platformBill.setOrderNo(orderNo);
                    platformBill.setAmount(amount);
                    platformBill.setType(FinancialEnum.IncomeOrExpend.Expend.name());//收入支出类型：0-收入，1-支出
                    platformBill.setEvent(FinancialEnum.PlatformBillEvent.PackageRefund.name());
                    platformBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
                    platformBill.setCreateTime(DateUtil.date());
                    platformBill.setComId(rechargeOrder.getComId());
                    platformBillService.saveRow(platformBill);

                    int giftAmount = (int)(rechargeOrder.getGiftAmount() * (amount * 1.0 / rechargeOrder.getPayAmount()));
                    //订单存在赠送金额，则需要按比例退掉赠送金额
                    if(giftAmount > 0){

                        Wallet giftWallet = new Wallet();
                        giftWallet.setComId(rechargeOrder.getComId());
                        giftWallet.setMemberUserId(rechargeOrder.getMemberUserId());
                        giftWallet.setOrderNo(rechargeOrder.getOrderNo());
                        giftWallet.setNo(OrderUtil.getOrderNo());
                        giftWallet.setAmount(giftAmount);
                        giftWallet.setType(FinancialEnum.IncomeOrExpend.Expend.name());
                        giftWallet.setEvent(FinancialEnum.WalletBillEvent.GiftRefund.name());
                        giftWallet.setStatus(FinancialEnum.BillStatus.Effective.name());
                        giftWallet.setCreateTime(DateUtil.date());
                        walletService.saveRow(giftWallet);

                        PlatformProfitBill profitBill = new PlatformProfitBill();
                        profitBill.setComId(rechargeOrder.getComId());
                        profitBill.setNo(OrderUtil.getOrderNo());
                        profitBill.setOutTradeNo(outTradeNo);
                        profitBill.setOrderNo(orderNo);
                        profitBill.setAmount(giftAmount);
                        profitBill.setType(FinancialEnum.IncomeOrExpend.Income.name());//收入支出类型：0-收入，1-支出
                        profitBill.setEvent(FinancialEnum.PlatformProfitBillEvent.GiftRefund.name());
                        profitBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
                        profitBill.setCreateTime(DateUtil.date());
                        platformProfitBillService.saveRow(profitBill);
                    }
                }

            }else {
                baofuRefund.setErrMsg(msg);
            }
            baofuRefund.setRefundState(refundState);
            service.saveRow(baofuRefund);
        }

    }

    public void chargeRefundBaofu( RechargeOrder rechargeOrder,Integer refundAmount){

    }

    /**
     * 校验是否进行分佣：白名单/被扣押订单/未设置结算订单，都不进行分佣
     *
     * @param order
     * @return
     */
    private boolean checkCommission(Order order) {
        //是否是免费订单
        if (isFreeOrder(order)) {
            return false;
        }
        return true;
    }

    /**
     * 是否是免费充电订单
     *
     * @param order
     * @return
     */
    private boolean isFreeOrder(Order order) {
        return YesOrNo.Yes.name().equals(StringUtil.getTrim(order.getIsFree()));
    }

    private void baofuRefund(BaofuRefund baofuRefund) {
        //查询明细数据
       List<BaofuAccountDetails> details = baofuAccountDetailsService.getRows(new String[]{"out_trade_no","account_type"}, new Object[]{baofuRefund.getOutTradeNo(),FinancialEnum.IncomeOrExpend.Income.name()});
       if(details!=null && details.size()>0){
           List<BaofuAccountDetails> addDetails =new ArrayList<>();
           ValuesActionEntity actionEntity = new ValuesActionEntity();
           List<ValuesAcctInfoEntity> acctInfo =  new ArrayList<>();
           ValuesAcctInfoEntity acctInfoEntity =  null;
           String transSerialNo =OrderUtil.getTxOrderNo();
           Integer dealAmount = 0;
           for(BaofuAccountDetails vo:details){
               acctInfoEntity = new ValuesAcctInfoEntity();
               acctInfoEntity.setContractNo(vo.getContractNo());
               acctInfoEntity.setTransAmount(new BigDecimal(vo.getCommission()).divide(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
               acctInfoEntity.setRemark("订单："+vo.getOutTradeNo()+"进行比退款");
               dealAmount = dealAmount + vo.getCommission();
               acctInfo.add(acctInfoEntity);
               //写人账户明细数据
               BaofuAccountDetails accountDetails = new BaofuAccountDetails();
               accountDetails.setCommissionId(vo.getCommissionId());
               accountDetails.setContractNo(vo.getContractNo());
               accountDetails.setCommission(vo.getCommission());
               accountDetails.setCommissionRate(vo.getCommissionRate());
               accountDetails.setChargeOrderId(vo.getChargeOrderId());
               accountDetails.setTransSerialNo(transSerialNo);
               accountDetails.setOutTradeNo(vo.getOutTradeNo());
               accountDetails.setOrderAmount(vo.getOrderAmount());
               accountDetails.setAccountType(FinancialEnum.IncomeOrExpend.Expend.name());
               accountDetails.setType(vo.getType());
               accountDetails.setCreateTime(new Date());
               //accountDetails.setBaofuAccountDetailsId(UUID.randomUUID().toString().replaceAll("-",""));
               addDetails.add(accountDetails);
           }
           actionEntity.setAcctInfo(acctInfo);
           actionEntity.setTransOrderNo("TSN"+ FormatUtil.CreateAeskey(20));
           actionEntity.setTransSerialNo(transSerialNo);
           actionEntity.setOrderNo(baofuRefund.getOutTradeNo());
           actionEntity.setDealAmount(new BigDecimal(dealAmount).divide(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
           ContentBodyEntity<RsultBodyEntity> contentBody = baoFuAccountService.BCT3_5002_001_01(actionEntity);
           if (contentBody.getBody().getState() == 1){
               //添加宝付流水
                if(addDetails!=null && addDetails.size()>0){
                    for(BaofuAccountDetails vo:addDetails){
                        accountDetailsService.saveRow(vo);
                    }
                }
           }
       }
    }
}
